package com.rc.saas.tenant.common.utils;

import java.util.UUID;

/**
 * Id生成器。将jdk内置UUID生成的uuid去'-'号，并将16进制表述转为62进制表述
 * Created by sven on 2018-02-17 11:11
 */
public final class UuidUtil {
    private static final String[] chars = new String[]{
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
            "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    public static String genUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String genShortUuid() {
        UUID uuid = UUID.randomUUID();
        long most = uuid.getMostSignificantBits();
        long least = uuid.getLeastSignificantBits();
        StringBuilder stringBuilder = new StringBuilder();
        int radix = 62;
        for (int i = 0; i < 11; i++) {
            int mi = (int) most % radix;
            int li = (int) (least % radix);

            stringBuilder.append(chars[mi < 0 ? (mi + 62) : mi]);
            stringBuilder.append(chars[li < 0 ? (li + 62) : li]);

            most = most / radix;
            least = least / radix;
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
        System.out.println(genShortUuid());
    }
}
